<?php

require_once ROOT_SERVICES . DS . 'shipping_provider_interface.php';
require_once ROOT_LIBRARY_HTMLDOM . DS . 'simple_html_dom.php';
require_once ROOT_LIBRARY_CURL . DS . 'curl.php';
require_once ROOT_LIBRARY_CURL . DS . 'curl_response.php';

// Thai post
class shipping_provider_3 implements shipping_provider_interface {

    private $_shipment;

    public function __construct($shipment) {
        $this->_shipment = $shipment;
    }

    public function get_status_shipping() {
        try
        {

            $tracking_number = $this->_shipment ['tracking_number'];
            $url = $this->_shipment ['url'] !== '' ? $this->_shipment ['url'] : 'http://track.thailandpost.co.th/trackinternet/Default.aspx?lang=en';
            $url_result = 'http://track.thailandpost.co.th/trackinternet/Result.aspx';

            $curl = new Curl();
            $response = $curl->get($url);
            $html = new simple_html_dom();
            $html->load($response->body);

            $params = array();
            foreach ($html->find('input') as $input) {
                $params[$input->name] = $input->value;
            }
            $params['Login.x'] = '55';
            $params['Login.y'] = '4';
            $params['TextBarcode'] = $tracking_number;
            $curl->post($url, $params);
            $response_result = $curl->get($url_result);

            $html->load($response_result->body);

            $status_list = array();
            $table_tr_e = $html->find('table#DataGrid1 tbody tr');

            if (is_array($table_tr_e)) {
                foreach ($table_tr_e as $tr) {
                    $tds = $tr->find('td');
                    $time = array_shift($tds);
                    $status = array_shift($tds);

                    if ($time && $status) {
                        $check_time_m = preg_match("/(\d{2}):(\d{2}):(\d{2})/", $time->plaintext, $matches);
                        if ($check_time_m) {
                            $status_list[] = array(
                                'time' => $time->plaintext,
                                'status' => "({$this->_shipment ['shipment_provider_name']}) " . $status->plaintext
                            );
                        }
                    }
                }
            }
            return array('sortable' => FALSE, 'status_list' => $status_list);
        } catch (Exception $e)
        {
            return array('sortable' => FALSE, 'status_list' => null);
        }
    }

}

?>
